package com.tcppag.linebased;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @author 罗俊华
 * @date 2021/8/27 - 9:14 上午
 */
@Slf4j
public class lineBasedFrameServer {

    /**
     * 基于换行符 处理 tcp 消息边界
     * @param args
     */
    public static void main(String[] args) {


        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {

                        ch.pipeline()
                                .addLast(new LoggingHandler())
                                /**
                                 * 基于换行符 处理 消息边界，要指定消息的最大长度
                                 * 如果超过这个长度还没有找到换行符，那么将抛出异常
                                 */
//                                .addLast(new LineBasedFrameDecoder(10240))
                                /**
                                 * DelimiterBasedFrameDecoder 作为 LineBasedFrameDecoder 的增强版
                                 * 可以自定义换行符，两者在这里用其中一个就可以了
                                 */
                                .addLast(new DelimiterBasedFrameDecoder(10240, ByteBufAllocator.DEFAULT.buffer().writeBytes("\n".getBytes(StandardCharsets.UTF_8)).asReadOnly()))
                                .addLast(new StringDecoder())
                                .addLast(new ChannelInboundHandlerAdapter(){
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        log.debug("收到换行后的消息：{}",msg.toString());
                                    }
                                });


                    }
                }).bind(9909);

    }
}
